<template>
  <div class="boxCard">
    <div v-if="!isLook" style="width: 100%; height: 100%">
      <el-card shadow="always">
        <div class="title">
          <span />
          <p>查询条件</p>
        </div>

        <el-form :model="seachForm" label-width="120px">
          <el-row :gutter="12">
            <el-col :span="6">
              <el-form-item label="网站名称：">
                <el-input v-model="seachForm.websiteName" placeholder="请输入网站名称" />
              </el-form-item>
            </el-col>

            <el-col :span="24" style="text-align: right">
              <el-button type="primary" @click="getInit(1)">查询</el-button>
              <el-button @click="rest">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <el-card shadow="always" style="
          margin-top: 15px;
          width: 100%;
          height: 77%;
          display: flex;
          flex-direction: column;
        ">
        <div class="header">
          <div class="title">
            <span />
            <p>网站列表</p>
          </div>

          <div>
            <el-button type="primary" size="small" @click="add">新增</el-button>
          </div>
        </div>

        <ul v-loading="loading" class="list" element-loading-text="正在加载...">
          <li v-for="(item, index) in dataList" :key="index">
            <div class="imageIcon">
              <img :src="item.atPresentImage" alt="" />
            </div>
            <div class="content">
              <div class="top">
                <h3>{{ item.websiteName }}</h3>
                <p>地址：{{ item.websiteaddress }}</p>
                <p>网站：{{ item.websiteInfo }}</p>
                <p>存入时间：{{ item.createTime }}</p>
              </div>
              <div class="bottom">
                <el-button type="text" @click="del(item)">删除</el-button>
                <el-button type="text" @click="uodate(item)">修改</el-button>
                <el-button type="text" @click="look(item)">浏览</el-button>
                <el-button type="text" @click="goAtPresent(item)">跳转</el-button>
              </div>
            </div>
          </li>
        </ul>
      </el-card>

      <el-dialog :visible.sync="showAddDialog" title="填写网站信息">
        <el-form ref="form" :model="addForm" label-width="120px" :rules="rules">
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="网站名称：" prop="websiteName">
                <el-input v-model="addForm.websiteName" placeholder="请输入网站名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="网站地址：" prop="websiteaddress">
                <el-input v-model="addForm.websiteaddress" placeholder="请输入网站地址" @input="websiteaddressChnage" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="网站介绍：" prop="websiteInfo">
                <el-input v-model="addForm.websiteInfo" type="textarea" placeholder="网站介绍：" />
              </el-form-item>
            </el-col>

            <el-col v-if="imageUrl" :span="12">
              <el-form-item label="识别图标：">
                <div class="imageClassBox">
                  <img :src="imageUrl" alt="加载失败" class="imageClass" @click="clickImage" />
                </div>
              </el-form-item>
            </el-col>

            <el-col v-if="addForm.atPresentImage" :span="12">
              <el-form-item label="当前图标：">
                <div class="imageClassBox">
                  <img :src="addForm.atPresentImage" class="imageClass" />
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="自定义图标：">
                <uploadFile @success="fileUpload_success" />
              </el-form-item>
            </el-col>

            <el-col :span="24" style="text-align: center; margin-top: 10px">
              <el-button size="small" type="primary" @click="save">确定</el-button>
              <el-button size="small" @click="showAddDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>

    <div v-if="isLook" style="width: 100%; height: 100%; position: relative">
      <iframe :src="lookObj.websiteaddress" frameborder="0" style="width: 100%; height: 100%" />

      <i class="el-icon-circle-close" style="
          position: absolute;
          top: 20px;
          right: 30px;
          font-size: 30px;
          color: brown;
        " @click="isLook = false" />
    </div>
  </div>
</template>

<script>
import { deleteFile, getUploadedFiles } from "@/api/chuizi";
import TableView from "@/components/TableView/index.vue";
import Item from "@/layout/components/Sidebar/Item.vue";
import uploadFile from "@/components/uploadFile.vue";
import { addWebsite, delWebsite, websiteList } from "@/api/website";
import { saveFileData } from "@/api/file";

export default {
  components: {
    TableView,
    uploadFile,
  },
  data() {
    return {
      dataList: [],
      loading: false,
      seachForm: {
        page: 1,
        size: 1000,
        total: 0,
      },
      showAddDialog: false,
      addForm: {
        atPresentImage: "",
      },
      isLook: false,
      lookObj: {},
      imageUrl: "",

      rules: {
        websiteName: [
          { required: true, message: "请输入网站名称", trigger: "blur" },
        ],
        websiteaddress: [
          { required: true, message: "请输入网站地址", trigger: "blur" },
        ],
        websiteInfo: [
          { required: true, message: "请输入网站介绍", trigger: "blur" },
        ],
      },
    };
  },

  mounted() {
    this.getInit();
  },

  methods: {
    async getInit(page) {
      this.seachForm.page = page || this.seachForm.page;
      this.loading = true;
      const res = await websiteList(this.seachForm);
      if (res.code == 20000) {
        this.dataList = res.data || [];
        this.seachForm.total = res.total;
      } else {
        this.$message.error(res.msg);
      }
      this.loading = false;
    },

    rest() {
      this.seachForm = {
        page: 1,
        size: 1000,
        total: 0,
      };
      this.getInit();
    },

    add() {
      this.addForm = {
        atPresentImage: "",
      };
      this.imageUrl = "";
      this.showAddDialog = true;
    },

    uodate(row) {
      this.addForm = { ...row };
      this.showAddDialog = true;
    },

    look(row) {
      this.lookObj = row;
      this.isLook = true;
    },

    // 跳转页面
    goAtPresent(row) {
      window.open(row.websiteaddress, "_blank");
    },

    // 保存按钮
    async save() {
      if (!this.addForm.atPresentImage) {
        this.$message.warning("请上传或选择图标");
        return;
      }

      this.$refs.form.validate(async (flag) => {
        if (flag) {
          const result = await addWebsite(this.addForm);
          if (result.code == 20000) {
            this.$message.success(result.msg);
            this.showAddDialog = false;
            this.getInit();
          } else {
            this.$message.error(result.msg);
          }
        }
      });
    },

    // 网址发生变化
    websiteaddressChnage(e) {
      const apiUrl = `https://logo.clearbit.com/${new URL(e).hostname}`;
      console.log(apiUrl, "apiUrl");
      this.imageUrl = apiUrl;
    },

    async clickImage() {
      try {
        // 使用 fetch 请求文件
        const response = await fetch(this.imageUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        // 获取文件的二进制数据
        const blob = await response.blob();

        // 从 URL 中提取文件名
        const fileName = this.imageUrl.split("/").pop();

        // 创建 File 对象
        const file = new File([blob], fileName, { type: blob.type });

        console.log("转换成功，File 对象:", file);

        const formData = new FormData();
        formData.append("file", file);
        const result = await saveFileData(formData);
        console.log(result, "result");
        if (result.code == 20000) {
          this.$message.success("已选择当前图标");
          this.addForm.atPresentImage = result.data.imageBase64; // 设置当前图标
          this.addForm.fileId = result.data.fileId; // 设置图标id
        }
      } catch (error) {
        console.error("转换失败:", error);
      }
    },

    // 文件上传成功
    fileUpload_success(e) {
      console.log(e);

      this.addForm.fileId = e.res.fileId;
      this.addForm.atPresentImage = e.res.imageBase64; // 设置当前图标
    },

    pagination(e) {
      this.seachForm = e;
      this.getInit();
    },

    // 点击删除按钮
    del(row) {
      this.$confirm("确定删除当前收藏网站吗？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      }).then(async () => {
        const res = await delWebsite({ id: row.id });

        if (res.code == 20000) {
          this.$message.success("删除成功");
          this.getInit();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 选择表格
    selectionChange(e) {
      this.selectTable = e;
    },
  },
};
</script>

<style scoped>
.list {
  width: 100%;
  flex: 1;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  overflow-y: auto !important;
  border-top: 1px solid transparent;
}

.list li {
  width: 100%;
  height: 170px;
  flex: 0 0 24%;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  padding: 10px;
  box-sizing: border-box;
  /* margin: 10px; */
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

@media screen and (max-width: 700px) {
  .list li {
    width: 98% !important;
    flex: 0 0 24%;
    height: 170px;
    box-shadow: 0 0 0px 0 rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    padding: 10px;
    box-sizing: border-box;
    margin: 0;
    border-bottom: 2px solid #f1f1f1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

@media screen and (min-width: 701px) and (max-width: 1100px) {
  .list li {
    flex: 0 0 48%;

    width: 48% !important;
  }
}

@media screen and (min-width: 1101px) and (max-width: 1500px) {
  .list li {
    flex: 0 0 32%;
    width: 32% !important;
  }
}

@media screen and (min-width: 1501px) {
  .list li {
    flex: 0 0 24%;
    width: 24% !important;
  }
}

.list li .imageIcon {
  width: 30%;
  height: 150px;
  border-right: 1px solid #f1f1f1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.list li .imageIcon img {
  height: 50%;
  border-radius: 10px;
}

.list li .content {
  flex: 1;
  height: 100%;
  color: #333;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.list li .content .top {
  width: 100%;
  flex: 1;
  border-bottom: 1px solid #f1f1f1;
  margin-top: 10px;
}

.list li .content .top h3 {
  font-size: 16px;
  width: 100%;
}

.list li .content .top p {
  font-size: 12px;
  margin: 5px 0;
  color: #666;
  width: 200px;
  white-space: nowrap;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.list li .content .bottom {
  width: 100%;
  height: 30px;
  font-size: 12px;
  /* text-align: right; */
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.imageClassBox {
  width: 100px;
  height: 100px;
  padding: 10px;
  box-sizing: border-box;
  overflow: hidden;
}

.imageClassBox .imageClass {
  height: 100%;
  width: 100%;
  border-radius: 10px;
}

>>>.el-card__body {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}
</style>
